<?php
//创建链接数据库的对象、属性、方法
	namespace KJ;
	
	class Db{
		private $_host;		/*私有属性*/
		private $_name;
		private $_pass;
		private $_charset;
		private $_db;
		private $_link;
		private static $_instance;		/*私有静态属性*/
		/*初始化设置*/
		/*构造函数实例化对象时自动加载*/
		private function __construct($config = array()){  
			$this->_host 	= isset($config['HOST']) ? $config['HOST'] : '127.0.0.1';
			$this->_name 	= isset($config['NAME']) ? $config['NAME'] : 'root';
			$this->_pass 	= isset($config['PASS']) ? $config['PASS'] : 'root';
			$this->_charset = isset($config['CHARSET']) ? $config['CHARSET'] : 'UTF8';
			$this->_db 		= isset($config['DB']) ? $config['DB'] : 'test';
			$this->initServer();
		}
		private function initServer(){
			$this->connect();
			$this->setCharset();
			$this->selectDb();
		}
		private function connect(){
			$conn = mysql_connect($this->_host , $this->_name ,$this->_pass);
			if(!$conn){
				die('数据库链接失败');
			}else{
				$this->_link = $conn;
			}
		}
		private function setCharset(){
			$sql = "SET NAMES $this->_charset";
			if(!$this->query($sql)){
				die('数据库字符集编码设置错误');
			}
		}
		private function selectDb(){
			if(!mysql_select_db($this->_db)){
				die('数据库不存在');
			}
		}
		public static function getInstance($config){
			if(!(static :: $_instance instanceof static)){
				static :: $_instance = new static($config);
			}
			return static :: $_instance;
		}
		public function query($sql){
			return mysql_query($sql,$this->_link);
		}
	}
?>